import store from './store.js'


const token = uni.getStorageSync('token'); //token
const api = store.state.globalApi; //请求域名
const updateApi = store.state.globalupApi; // 上传文件地址
const authentication = store.state.requestHeader; //token key


/**
 * @author 晨昱
 * uni.request封装
 */
export const request = (options) => {
	return new Promise((resolve, reject) => {
		if (!options.url) {
			throw new Error("请传入URL!");
			return;
		}
		if (!options.method) {
		}
		
		var token = uni.getStorageSync('token');
		var url = api + options.url
		var that = this
		// if(options.url=='register' ||options.url=='register_send_sms'   ){
		// 	token = ''
		// }
		uni.request({
			url: url,
			method: options.method || 'POST',
			data: options.data || '',
			header: {
				  "content-type":"application/json",
				"token": token
			},
			success: (res) => {
				if (res.statusCode < 500) {
					if(res.data.code !=200){
							uni.showToast({
								title: res.data.msg,
								icon:'none'
							})
					} else {
						
					}
					resolve(res.data);
				} else {
					uni.showToast({
						title: '服务器错误',
						icon:'none'
					})
					uni.hideLoading()
					throw new Error("服务器错误,请检查");
					console.error(res);
				}
			},
			
			fail: (err) => {
				uni.showToast({
					title: '请求失败',
					icon:'none'
				})
				reject(err)
			}
		})
	})
}

export const changeToken = () => {
	return new Promise((resolve,reject) => {
		let token = uni.getStorageSync('token');
		if(uni.getStorageSync('account') && uni.getStorageSync('psw') ) {
			var data =  { //请求参数
					'phone': uni.getStorageSync('account'),
					'password': uni.getStorageSync('psw'),
				};
				console.log(data)
			uni.request({
				url: api + 'phone_login',
				method: 'POST',
				data: data,
				header: {
					"Content-Type": store.state.requestHeader,
				},
				success: (res) => {
					if (res.data.code == 1) {
						uni.setStorageSync('token', '') 
						uni.setStorageSync('token', res.data.data.token) //data 是具体内容
						console.log('token1111', res.data.data.token)
					} else {}
				},
				fail: (err) => {
					console.error(err);
				}
			})
		}
	})
}


/**
 * @author 晨昱 木可
 * 上传图片 阿里oss方式
 */
export const uploadImage = (event) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token')
		var pathList = [];
		uni.chooseImage({
			count: event.count || 9,
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				uni.showLoading({
					title: '上传中'
				})
				for (let i = 0; i < tempFilePaths.length; i++) {
					let index = tempFilePaths[i].lastIndexOf(".")
					let suffix = tempFilePaths[i].substr(index + 1)
					let fileList = uni.getStorageSync('userinfo').id + '/' + Math.random().toString(
							36).substr(2) +
						'.' + suffix
					uni.request({
							url: api + 'upload/get_sign',
							data: {
							},
							method: 'POST',
							header: {
								"Content-Type": store.state.requestHeader,
								authentication: token
							},
						})
						.then((res) => {
							console.log('获取签名成功',res)
							uni.uploadFile({
								url: '/api2',
								filePath: tempFilePaths[i],
								name: event.name ? event.name : 'file',
								formData: {
									'key': fileList,
									'policy': res[1].data.data.policy, // 输入你获取的的policy
									'OSSAccessKeyId': res[1].data.data.accessId, // 输入你的AccessKeyId
									'success_action_status': 200, // 让服务端返回200,不然，默认会返回204
									'signature': res[1].data.data.signature // 输入你获取的的signature
								},
								header: {
									"Content-Type": "multipart/form-data",
									authentication: token
								},
								success: (uploadFileRes) => {
									console.log(uploadFileRes)
									let key = res[1].data.data + fileList
									let breviary = res[1].data.data +
										fileList +
										'?x-oss-process=image/resize,s_600,m_fill,limit_0'
									let square = res[1].data.data +
										fileList +
										'?x-oss-process=image/resize,s_600,m_fill,limit_0'
									pathList.splice(i, 0, {
										type: 0,
										key: key,
										breviary: breviary,
										square: square
									})
									if (pathList.length == tempFilePaths
										.length) {
										resolve(pathList)
										uni.hideLoading();
									}
								},
								fail(e){
									console.log('上传失败',e)
									alert(e)
								}
							})
						})
				}
			}
		});
	})
}



/**
 * @autor 晨昱 木可
 * 上传图片 阿里oss方式 h5
 */
export const uploadImageH5 = (event) => {
	return new Promise((resolve, reject) => {
		console.log('uploadImageH5',)
		const token = uni.getStorageSync('token')
		var pathList = [];
		uni.chooseImage({
			count: event.count || 9,
			success: (chooseImageRes) => {
				
				const tempFilePaths = chooseImageRes.tempFilePaths;
				const tempFiles = chooseImageRes.tempFiles;
				uni.showLoading({
					title: '上传中'
				})
				let obj = new Date()
				let day = obj.getDate()
				let month = obj.getMonth() + 1
				let year = obj.getFullYear()
				for (let i = 0; i < tempFilePaths.length; i++) {
					
					let index = tempFiles[i].name.lastIndexOf(".")
					let suffix = tempFiles[i].name.substr(index + 1)
					let fileList =  Math.random().toString(36).substr(2) +
						'.' + suffix
						console.log('tempFilePaths[i]',tempFilePaths[i])
					
					uni.request({   //对接天野接口实例，根据项目修改
							url: api + 'upload/get_sign',
							data: {
							},
							method: 'POST',
							header: {
								"Content-Type": store.state.requestHeader,
								Authentication : token
							},
						})
						.then((res) => {
							// console.log('res',res)
							uni.uploadFile({
								url: res[1].data.data.host,
								filePath: tempFilePaths[i],
								name: event.name ? event.name : 'file',
								formData: {
									'key': fileList,
									'policy': res[1].data.data.policy, // 输入你获取的的policy
									'OSSAccessKeyId': res[1].data.data.accessid, // 输入你的AccessKeyId
									'success_action_status': 200, // 让服务端返回200,不然，默认会返回204
									'signature': res[1].data.data.signature // 输入你获取的的signature
								},
								header: {
									Authentication : token
								},
								success: (uploadFileRes) => {
									// console.log('uploadFileRes',uploadFileRes)
									let key = res[1].data.data.host+ fileList
									let breviary = res[1].data.data.host + fileList +
										'?x-oss-process=image/resize,s_600,m_fill,limit_0'
									let square = res[1].data.data.host + fileList +
										'?x-oss-process=image/resize,s_600,m_fill,limit_0'
									pathList.splice(i, 0, {
										type: 0,
										key: key,
										breviary: breviary,
										square: square
									})
									// console.log('上传成功',pathList)
									if (pathList.length == tempFilePaths.length) {
										resolve(pathList)
										uni.hideLoading();
									}
								},
								fail:(err)=>{
									console.log('上传失败',err)
								}
							})
						})
				}
			},
			fail(e) {
				console.log('eeeeeee',e)
			}
			
		});
	})
}

/**
 * @author 晨昱 木可
 * 上传视频
 */
export const uploadVideo = (event) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('userInfo').token
		var video = []
		uni.chooseVideo({
			count: 1,
			success: (chooseVideoRes) => {
				const tempFilePath = chooseVideoRes.tempFilePath;
				uni.showLoading({
					title: '上传中'
				})
				let obj = new Date()
				let day = obj.getDate()
				let month = obj.getMonth() + 1
				let year = obj.getFullYear()
				// for (let i = 0; i < tempFilePath.length; i++) {
				let index = tempFilePath.lastIndexOf(".")
				let suffix = tempFilePath.substr(index + 1)
				let fileList = year + '/' + month + '/' + day + Math.random().toString(32)
					.substr(2) +
					'.' + suffix
				uni.request({
					url: api + 'oss_getSign',
					data: {
						token: token
					},
					method: 'POST',
					header: {
						"Content-Type": "application/json"
					},
					success: (res) => {
						uni.uploadFile({
							url: updateApi,
							filePath: tempFilePath,
							name: event.name ? event.name : 'file',
							formData: {
								'key': fileList,
								'policy': res.data.data
								.policy, // 输入你获取的的policy
								'OSSAccessKeyId': res.data.data
								.accessid, // 输入你的AccessKeyId
								'success_action_status': 200, // 让服务端返回200,不然，默认会返回204
								'signature': res.data.data
									.signature // 输入你获取的的signature
							},
							header: {
								"Content-Type": store.state.requestHeader,
								authentication: token
							},
							success: (uploadFileRes) => {
								let key = updateApi + fileList
								let breviary = updateApi + fileList +
									'?x-oss-process=video/snapshot,t_1000,f_jpg'
								let square = updateApi + fileList +
									'?x-oss-process=video/snapshot,t_1000,f_jpg'
								video.push({
									type: 1,
									key: key,
									breviary: breviary,
									square: square
								})
								resolve(video);
								console.log(video);
							}
						});
					}
				})
			}
		});
	})
}
/**
 * @author 晨昱
 * 不调起相册的上传图片方法
 */
export const upimg = (event) => {
	return new Promise((resolve, reject) => {
		if (event.url) {
			let obj = new Date()
			let day = obj.getDate()
			let month = obj.getMonth() + 1
			let year = obj.getFullYear()
			let index = event.url.lastIndexOf(".");
			let suffix = event.url.substr(index + 1);
			let fileList = uni.getStorageSync('userinfo').id + '/' + Math.random().toString(36).substr(2) +
				'.' + suffix
			uni.request({
					url: api + 'oss_getSign',
					data: {
						token: token
					},
					method: 'POST',
					header: {
						"Content-Type": store.state.requestHeader
					},
				})
				.then((res) => {
					console.log('签名')
					console.log(res);
					uni.uploadFile({
						url: updateApi,
						filePath: event.url,
						name: event.name ? event.name : 'file',
						formData: {
							'key': fileList,
							'policy': res[1].data.data.policy, // 输入你获取的的policy
							'OSSAccessKeyId': res[1].data.data.accessid, // 输入你的AccessKeyId
							'success_action_status': 200, // 让服务端返回200,不然，默认会返回204
							'signature': res[1].data.data.signature // 输入你获取的的signature
						},
						header: {
							"Content-Type": "multipart/form-data",
							"token": uni.getStorageSync('token')
						},
						success: (uploadFileRes) => {
							let key = updateApi + fileList;
							resolve(key)
							uni.hideLoading();
						}
					})
				})
		} else {
			console.error("请传入URL");
			reject(undefined);
		}
	});
}
